<template>
  <div class="order-comments">
    <h1 class="page-title">订单评论页面</h1>
    <div class="table-container">
      <!-- 查询表单 -->
      <el-card class="search-card">
        <el-form :model="queryForm" inline @submit.prevent="fetchOrderComments">
          <el-form-item label="订单ID">
            <el-input 
              v-model="queryForm.workOrderId" 
              placeholder="请输入订单ID" 
              clearable 
              @keyup.enter="fetchOrderComments"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="评论内容">
            <el-input 
              v-model="queryForm.content" 
              placeholder="请输入评论内容" 
              clearable 
              @keyup.enter="fetchOrderComments"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchOrderComments" :loading="loading">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 刷新按钮 -->
      <div style="margin: 15px 0;">
        <el-button type="primary" @click="fetchOrderComments" :loading="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </el-button>
      </div>

      <!-- 评论表格 -->
      <el-table :data="commentsList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="评论ID" width="80" />
        <el-table-column prop="workOrderId" label="订单ID" width="80">
          <template #default="scope">
            <el-link type="primary" @click="goToOrderDetail(scope.row.workOrderId)">
              {{ scope.row.workOrderId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" />
        <el-table-column prop="starRating" label="评分" width="180">
          <template #default="scope">
            <el-rate
              v-model="scope.row.starRating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}星"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评论时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button 
              size="small" 
              :type="scope.row.isValid === 0 ? 'success' : 'warning'"
              @click="handleToggleCommentVisibility(scope.row)"
            >
              {{ scope.row.isValid === 0 ? '显示' : '隐藏' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteComment(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: center;"
      />
    </div>

    <!-- 评论详情对话框 -->
    <el-dialog title="评论详情" v-model="detailDialogVisible" width="500px">
      <el-form :model="detailForm" label-width="100px" v-loading="detailLoading">
        <el-form-item label="评论ID">
          <span>{{ detailForm.id }}</span>
        </el-form-item>
        <el-form-item label="订单ID">
          <el-link type="primary" @click="goToOrderDetail(detailForm.workOrderId)">
            {{ detailForm.workOrderId }}
          </el-link>
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input 
            type="textarea" 
            v-model="detailForm.content" 
            :rows="4" 
            readonly
          />
        </el-form-item>
        <el-form-item label="评分">
          <el-rate
            v-model="detailForm.starRating"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}星"
          />
        </el-form-item>
        <el-form-item label="评论状态">
          <el-tag :type="detailForm.isValid === 0 ? 'danger' : 'success'">
            {{ detailForm.isValid === 0 ? '已隐藏' : '显示中' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="评论时间">
          <span>{{ formatDate(detailForm.createTime) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderCommentsAPI, toggleOrderCommentVisibilityAPI, deleteOrderCommentAPI } from '@/apis/order'
import { formatDate } from '@/utils/date'

export default {
  name: 'OrderComments',
  data() {
    return {
      commentsList: [],
      loading: false,
      detailDialogVisible: false,
      detailLoading: false,
      detailForm: {
        id: '',
        workOrderId: '',
        content: '',
        starRating: 0,
        createTime: ''
      },
      queryForm: {
        workOrderId: '',
        content: ''
      },
      queryTimer: null,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  mounted() {
    this.fetchOrderComments()
  },
  methods: {
    async fetchOrderComments() {
      this.loading = true
      try {
        // 构造查询参数
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        
        // 添加可选的查询条件
        if (this.queryForm.workOrderId) {
          params.workOrderId = this.queryForm.workOrderId
        }
        if (this.queryForm.content) {
          params.content = this.queryForm.content
        }
        
        const res = await getOrderCommentsAPI(params)
        if (res.code === 0) {
          this.commentsList = res.data.records.map(item => {
            return {
              id: item.id,
              workOrderId: item.workOrderId,
              content: item.content,
              starRating: item.starRating,
              createTime: item.createTime,
              isValid: item.isValid  // 添加评论有效性字段
            }
          })
          this.pagination.total = res.data.total
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取订单评论列表失败'
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取订单评论列表失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取订单评论列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 防抖查询
    debounceQuery() {
      if (this.queryTimer) {
        clearTimeout(this.queryTimer)
      }
      
      this.queryTimer = setTimeout(() => {
        this.pagination.currentPage = 1
        this.fetchOrderComments()
      }, 300)
    },
    
    // 重置查询
    resetQuery() {
      this.queryForm = {
        workOrderId: '',
        content: ''
      }
      this.pagination.currentPage = 1
      this.fetchOrderComments()
    },
    
    // 查看详情
    handleViewDetail(row) {
      this.detailForm = { ...row }
      this.detailDialogVisible = true
    },
    
    // 切换评论可见性
    handleToggleCommentVisibility(row) {
      const newVisibility = row.isValid === 0 ? 1 : 0;
      const actionText = newVisibility === 0 ? '隐藏' : '显示';
      
      this.$confirm(`确定要${actionText}这条评论吗？`, `${actionText}评论`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await toggleOrderCommentVisibilityAPI(row.id, newVisibility)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: `${actionText}评论成功!`
            })
            // 重新获取列表数据
            this.fetchOrderComments()
          } else {
            this.$message({
              type: 'error',
              message: res.msg || `${actionText}评论失败`
            })
          }
        } catch (error) {
          // 检查是否是HTTP响应错误对象
          let errorMessage = '未知错误';
          if (error.msg) {
            errorMessage = error.msg;
          } else if (error.message) {
            errorMessage = error.message;
          } else if (error.toString && error.toString() !== '[object Object]') {
            errorMessage = error.toString();
          }
          
          this.$message({
            type: 'error',
            message: `${actionText}评论失败: ` + errorMessage
          })
          console.error(`${actionText}评论失败:`, error)
        }
      }).catch(() => {
        // 用户取消操作
        this.$message({
          type: 'info',
          message: `已取消${actionText}`
        })
      })
    },
    
    // 跳转到订单详情
    goToOrderDetail(orderId) {
      this.$router.push({
        name: 'OrderDetail',
        query: {
          id: orderId
        }
      })
    },
    
    // 删除评论
    handleDeleteComment(row) {
      this.$confirm(`确定要删除这条评论吗？此操作无法撤销。`, '删除评论', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteOrderCommentAPI(row.id)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '删除评论成功!'
            })
            // 重新获取列表数据
            this.fetchOrderComments()
          } else {
            this.$message({
              type: 'error',
              message: res.msg || '删除评论失败'
            })
          }
        } catch (error) {
          // 检查是否是HTTP响应错误对象
          let errorMessage = '未知错误';
          if (error.msg) {
            errorMessage = error.msg;
          } else if (error.message) {
            errorMessage = error.message;
          } else if (error.toString && error.toString() !== '[object Object]') {
            errorMessage = error.toString();
          }
          
          this.$message({
            type: 'error',
            message: '删除评论失败: ' + errorMessage
          })
          console.error('删除评论失败:', error)
        }
      }).catch(() => {
        // 用户取消操作
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.fetchOrderComments()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchOrderComments()
    },
    
    // 格式化时间
    formatDate(date) {
      return formatDate(date)
    }
  }
}
</script>

<style scoped>
.order-comments {
  padding: 20px;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.search-card {
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

.dialog-footer {
  text-align: center;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
}
</style>